package com.study.mike.common.utils;

import cn.hutool.core.util.StrUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * 创建sessionId
 * @author kh
 */
public class SessionIdUtil {
    public static String getSessionId(HttpServletRequest request) {
        // request为空返回null
        if (Objects.isNull(request)) {
            return null;
        }
        // 优先取请求里的JSSESSIONID
        String sessionId = request.getRequestedSessionId();
        // 如果为空，需要新建一个
        if (StrUtil.isBlank(sessionId)) {
            HttpSession httpSession = request.getSession();
            // 为空返回null
            if (Objects.isNull(httpSession)) {
                return null;
            }
            sessionId = httpSession.getId();
        }
        return sessionId;
    }
}
